package com.huang.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{

    private int port;
    private String name;

    public TalkReceive(int port, String name) {
        this.port = port;
        this.name = name;
    }

    @Override
    public void run() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }

        //准备接受包裹
        while (true){

            try {
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(packet);
                String data = new String(packet.getData(), 0, packet.getData().length);
                System.out.println(name+"说：  "+data);
                if(data.equals("bye")){
                    break;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       socket.close();
    }
}
